/**
 * @ObjectPool.as
 * 
 * @author sodaChen mail:sujun10#21cn.com
 * @version 1.0
 * <br>Copyright (C), 2010 asFrame.com
 * <br>This program is protected by copyright laws.
 * <br>Program Name:挂机冒险
 * <br>Date:2014-6-15
 */
package com.asframe.pool
{
	import com.asframe.utils.DestroyUtils;

	/**
	 * 普通对象池
	 * @author sodaChen
	 * Date:2014-6-15
	 */
	public class ObjectPool implements IObjectPool
	{
		/** 用到池的对象的class **/
		private var _clazz:Class;
		private var _maxIdle:int;
		private var _idleObjects:Array;
		private var _hasStatus:Boolean;
		private var tempObj:*;
		
		/**
		 * 创建一个通用对象池实例
		 * @param clazz 使用对象的class
		 * @param maxIdle 最大缓存数量
		 * @param hasStatus 是否需要做状态检测（默认为false，如果没有状态，设置false会提升性能）
		 * 
		 */
		public function ObjectPool(clazz:Class,maxIdle:int = 100,hasStatus:Boolean = false)
		{
			this._clazz = clazz;
			this._maxIdle = maxIdle;
			this._hasStatus = hasStatus;
			_idleObjects = [];
		}
		
		public function borrowObject(): *
		{
			if(_idleObjects.length == 0)
			{
				tempObj = new _clazz();
			}
			else
			{
				tempObj = _idleObjects.pop();
			}
			//具备激活接口的对象
			if(_hasStatus && tempObj is IActivate)
				IActivate(tempObj).activate();
			
			return tempObj;
		}
		
		public function returnObject(obj:* ):void
		{
			if(isFull(obj))
			{
				DestroyUtils.destroyObj(obj);
			}
			else
			{
				if(_hasStatus && obj is IPassivate)
					IPassivate(obj).passivate();
				
				_idleObjects.push(obj);
			}
		}
		
		public function getNumIdle():int
		{
			return _idleObjects.length;
		}
		
		public function clear():void
		{
			destroy();
			_idleObjects = [];
		}
		
		public function isFull(obj:* ):Boolean
		{
			if(_idleObjects.length > _maxIdle)
			{
				return true;
			}
			
			return false;
		}
		
		public function destroy(o:* =null):void
		{
			for (var i:int = 0; i < _idleObjects.length; i++) 
			{
				DestroyUtils.destroyObj(_idleObjects[i]);
			}
			_idleObjects = null;
		}
	}
}